package com.hr.service.impl;

import com.hr.domain.po.UserLoginLog;
import com.hr.domain.vo.LoginUserVO;
import com.hr.mapper.UserLoginLogMapper;
import com.hr.mapper.UserMapper;
import com.hr.service.LoginService;
import com.hr.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import com.hr.utils.JwtUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@AllArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final UserMapper userMapper;

    private final UserLoginLogMapper userLoginLogMapper ;

    @Override
    public LoginUserVO login(String username, String password) {
        LoginUserVO loginUserVO  = userMapper.SelectByIdAndusername(username, password);


        if (loginUserVO == null){
            return null;
        }

        if (loginUserVO.getStatus() == 0){
            return null;
        }



            //生成Jwt令牌
            //1.传入自定义负载数据
            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("username",loginUserVO.getUsername());
            dataMap.put("userId",loginUserVO.getId() );//用户id
            dataMap.put("roleId", loginUserVO.getRoleId());//角色id
            //2.生成Jwt令牌
            String jwt = JwtUtils.generateJwt(dataMap);

            //保存登录日志
            Long roleId = userMapper.SelectById(loginUserVO.getId()).getRoleId();
            UserLoginLog userLoginLog = new UserLoginLog();
            if (roleId == 1L || roleId == 2L){
                //如果用户角色为房东和租户，登录来源为1--客户端
                userLoginLog.setLoginSource(1);
            }
            if (roleId == 3L){
                //如果用户角色为管理员，登录来源为2--后台
                userLoginLog.setLoginSource(2);
            }
            userLoginLog.setUserId(loginUserVO.getId());
            userLoginLog.setToken(jwt);
            userLoginLog.setLoginTime(LocalDateTime.now());
            //过期时间为当前时间加7天
            userLoginLog.setExpiresAt(LocalDateTime.now().plusDays(7));
            userLoginLog.setLogoutTime(null);
            userLoginLogMapper.addUserLoginLog(userLoginLog);


            //3.返回给前端
            return LoginUserVO.builder()
                    .realName(loginUserVO.getRealName())
                    .id(loginUserVO.getId())//用户id
                    .rname(loginUserVO.getRname())//角色名
                    .roleId(loginUserVO.getRoleId())
                    .username(loginUserVO.getUsername())//用户名
                    .token(jwt)//令牌
                    .build();

    }
}
